package com.fingerchar.api.service;

import com.fingerchar.db.dao.ext.FcUserExtMapper;
import com.fingerchar.db.domain.TtUsdtRecharge;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigInteger;

/**
 * @author tangzf
 * @date 2022/9/5
 */
@Service
@Slf4j
public class TtUsdtService {


    @Resource
    public TtUsdtRechargeService ttUsdtRechargeService;
    @Resource
    public FcUserExtMapper fcUserExtMapper;
    @Resource
    private FcUserService fcUserService;


    @Transactional
    public synchronized void recharge(String hash, String address, BigInteger amount) {


        TtUsdtRecharge fcUsdtRecharge = ttUsdtRechargeService.getByHash(hash);
        if (null != fcUsdtRecharge) {
            log.error("address:{}, hash:{}, 充值记录已存在",address, hash);
            return;
        }
        //todo 通过web3校验充值记录； 锁的逻辑改成锁  地址
        int insRow = ttUsdtRechargeService.insert(hash, address, amount, "0");
        int updRow = fcUserService.addUsdtAmount(address, amount);
        if (1 != insRow || 1 != updRow) {
            throw new RuntimeException("充值失败");
        }
    }

    public synchronized void withdraw(String hash, String address, BigInteger amount){
        TtUsdtRecharge fcUsdtRecharge = ttUsdtRechargeService.getByHash(hash);
        if (null != fcUsdtRecharge) {
            log.error("address:{}, hash:{}, 提现记录已存在",address, hash);
            return;
        }
        //todo 通过web3校验充值记录； 锁的逻辑改成锁  地址

        //DappWeb3jUtil.getErc20Info();

        int insRow = ttUsdtRechargeService.insert(hash, address, amount, "1");
        int updRow = fcUserService.reduceUsdtAmount(address, amount);
        if (1 != insRow || 1 != updRow) {
            throw new RuntimeException("提现扣减失败");
        }
    }
}
